import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yn_goods/base/widget/base_list_more_get_builder.dart';
import 'package:flutter_yn_goods/config/app_color.dart';
import 'package:flutter_yn_goods/config/app_routes.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:flutter_yn_goods/pages/mine_visit/model/model_visit_list.dart';
import 'package:flutter_yn_goods/utils/utils_other.dart';
import 'package:flutter_yn_goods/widgets/appbar/common_app_bar.dart';
import 'package:flutter_yn_goods/widgets/image/image_view.dart';
import 'package:get/get.dart';

import 'mine_visit_logic.dart';

class MineVisitPage extends StatelessWidget {
  final logic = Get.put(MineVisitLogic(), tag: MineVisitLogic.tag);

  MineVisitPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonAppBar(
        title: LocaleKeys.my_visit_records.tr,
        actions: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              logic.toggleManageMode();
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 8.w),
              alignment: Alignment.center,
              child: Obx(() => Text(
                    logic.isManageMode.value
                        ? LocaleKeys.cancel.tr
                        : LocaleKeys.manage.tr,
                    style: TextStyle(
                      color: AppColor.color282828,
                      fontSize: 14.sp,
                    ),
                  )),
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: _buildVisitList(),
          ),
          // 底部管理操作栏，在管理模式下显示
          Obx(() {
            return logic.isManageMode.value ? _buildBottomBar() : SizedBox();
          }),
        ],
      ),
    );
  }

  Widget _buildVisitList() {
    return BaseListMoreGetBuilder<MineVisitLogic>(
      tag: MineVisitLogic.tag,
      enablePullDown: true,
      enablePullUp: true,
      initialRefresh: true,
      builder: (controller) {
        // if (controller.list.isEmpty) {
        //   return Center(child: CircularProgressIndicator());
        // }

        return ListView.builder(
          padding: EdgeInsets.all(16.w),
          itemCount: controller.groupedData.length,
          itemBuilder: (context, index) {
            String dateKey = controller.groupedData.keys.elementAt(index);
            List<ModelVisitList> items = controller.groupedData[dateKey] ?? [];

            return _buildDateGroup(dateKey, items);
          },
        );
      },
    );
  }

  Widget _buildDateGroup(String dateKey, List<ModelVisitList> items) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 日期标题
        Container(
          margin: EdgeInsets.only(bottom: 12.w),
          child: Text(
            dateKey,
            style: TextStyle(
              color: AppColor.color282828,
              fontSize: 16.sp,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        // 网格布局展示商品
        GridView.builder(
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            childAspectRatio: 0.6,
            crossAxisSpacing: 8.w,
            mainAxisSpacing: 8.w,
          ),
          itemCount: items.length,
          itemBuilder: (context, index) {
            return _buildVisitItem(items[index]);
          },
        ),
        SizedBox(height: 20.w),
      ],
    );
  }

  Widget _buildVisitItem(ModelVisitList item) {
    return GestureDetector(
      onTap: () {
        if (logic.isManageMode.value) {
          // 管理模式下，点击选择商品
          logic.toggleItemSelection(item);
        } else {
          // 非管理模式下，点击进入商品详情
          Get.toNamed(AppRoutes.goodsInfoPage,
              arguments: {'id': item.productId});
        }
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8.w),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 4,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 商品图片
            Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(8.w),
                    topRight: Radius.circular(8.w),
                  ),
                  child: ImageView(
                    imageUrl: item.image,
                    width: double.infinity,
                    height: 110.w,
                    fit: BoxFit.cover,
                  ),
                ),
                // 管理模式下显示选择框
                Obx(() {
                  return logic.isManageMode.value
                      ? Positioned(
                          top: 5.w,
                          right: 5.w,
                          child: Container(
                            width: 20.w,
                            height: 20.w,
                            decoration: BoxDecoration(
                              color: item.isSelected
                                  ? AppColor.primary
                                  : Colors.white,
                              shape: BoxShape.circle,
                              border: Border.all(
                                color: item.isSelected
                                    ? AppColor.primary
                                    : Colors.grey,
                                width: 1.5,
                              ),
                            ),
                            child: item.isSelected
                                ? Icon(
                                    Icons.check,
                                    color: Colors.white,
                                    size: 14.w,
                                  )
                                : null,
                          ),
                        )
                      : SizedBox();
                }),
              ],
            ),
            // 商品信息
            Padding(
              padding: EdgeInsets.all(8.w).copyWith(bottom: 0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 商品价格
                  Text(
                    UtilsOther.getGoodsPrice(item.productPrice),
                    // '¥${item.productPrice ?? ''}',
                    style: TextStyle(
                      color: AppColor.primary,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(height: 4.w),
                  // 商品名称
                  Text(
                    item.storeName ?? '',
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: AppColor.color282828,
                      fontSize: 12.sp,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBottomBar() {
    return Container(
      height: 56.h,
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: Offset(0, -1),
          ),
        ],
      ),
      child: Row(
        children: [
          // 全选
          GestureDetector(
            onTap: () {
              logic.toggleSelectAll();
            },
            child: Row(
              children: [
                Obx(() {
                  return Checkbox(
                    value: logic.isAllSelected.value,
                    onChanged: (value) {
                      logic.toggleSelectAll();
                    },
                    activeColor: AppColor.primary,
                  );
                }),
                Text(
                  LocaleKeys.select_all.tr,
                  style: TextStyle(
                    color: AppColor.color282828,
                    fontSize: 14.sp,
                  ),
                ),
              ],
            ),
          ),
          SizedBox(width: 8.w),
          // 已选数量
          Obx(() {
            return Text(
              '${LocaleKeys.selected.tr}: ${logic.selectedCount.value}',
              style: TextStyle(
                color: AppColor.color666666,
                fontSize: 14.sp,
              ),
            );
          }),
          Spacer(),
          // 删除足迹按钮
          GestureDetector(
            onTap: () {
              logic.batchDeleteVisit();
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
              decoration: BoxDecoration(
                color: AppColor.primary,
                borderRadius: BorderRadius.circular(20.w),
              ),
              child: Text(
                LocaleKeys.remove_visit.tr,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
